﻿(function (module) {
    var ctrl = function ($log, $scope, $rootScope, $state, $window) {
        var currentStateName = $state.current.name;

        $log.debug('nestedValidationController.ctor:', $state.params);

        $scope.$on('$destroy', function () {
            $log.debug('nestedValidationController.$destroy');
        });

        $scope.name = '';

        $scope.types = ['person', 'company'];
        $scope.selectedType = 'person';
        $scope.financeInfo = null;

        $scope.$watch('selectedType', function () {
            $log.debug('selectedType changed', $scope.selectedType);

            if ($scope.selectedType === 'person')
            {
                $rootScope.safeApply($scope, function () {
                    $scope.financeInfo = {
                        dataType: 'personForm',
                        fiscalCode: ''
                    };
                });
            } else {
                $rootScope.safeApply($scope, function () {
                    $scope.financeInfo = {
                        dataType: 'companyForm',
                        fiscalCode: '',
                        vatId: ''
                    };
                });
            }
        });

        $scope.onSubmit = function () {
            $log.debug('onSubmit');

            $window.alert('outer & nested forms are valid, form submitted!');
        };
    };
    ctrl.$inject = ['$log', '$scope', '$rootScope', '$state', '$window'];

    module.controller('nestedValidationController', ctrl);
}(angular.module('topics.controllers')));
